package com.app.teaware.ware;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Parcelable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.app.teaware.R;
import com.app.teaware.basis.BasisActivity;
import com.app.teaware.basis.Constants;
import com.app.teaware.bean.BaseListBean;
import com.app.teaware.bean.BaseListBeanXF;
import com.app.teaware.bean.BasisBean;
import com.app.teaware.bean.GoodsListData;
import com.app.teaware.bean.GoodsWorks;
import com.app.teaware.bean.LoginBean;
import com.app.teaware.bean.MenuBean;
import com.app.teaware.bean.StockListBean;
import com.app.teaware.bean.StockListData;
import com.app.teaware.bean.WareListBean;
import com.app.teaware.bean.WareListData;
import com.app.teaware.bean.WorkListBean;
import com.app.teaware.bean.WorkListData;
import com.app.teaware.goods.AddOrEditGoodsActivity;
import com.app.teaware.goods.AddOrEditGoodsInfoActivity;
import com.app.teaware.goods.GoodsListActivity;
import com.app.teaware.greendao.GreenDaoUtils;
import com.app.teaware.multiselection.TypeLabelGridLayout;
import com.app.teaware.util.MyUtils;
import com.app.teaware.util.OnClickUtils;
import com.app.teaware.util.ReceiverUtils;
import com.app.teaware.util.SplitUtil;
import com.app.teaware.util.UHFUtil;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.google.gson.Gson;
import com.jcodecraeer.xrecyclerview.ProgressStyle;
import com.jcodecraeer.xrecyclerview.XRecyclerView;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import my.ActivityTool;
import my.DialogUtils;
import my.TimeUtils;
import my.ViewUtils;
import my.http.MyHttpListener;
import my.http.MyHttpUtils;
import my.http.MyParams;

/**
 * 库存查询
 */
public class WareListActivity extends BasisActivity {

    @BindView(R.id.recyclerview)
    XRecyclerView mRecyclerView;
    private MyAdapterList mAdapter;
    private WareListBean mListBean;

    @BindView(R.id.lgl_label)
    TypeLabelGridLayout lglLabel;
    @BindView(R.id.view_multi)
    View view_multi;

    @BindView(R.id.text_start_time)
    TextView textStartTime;
    @BindView(R.id.text_end_time)
    TextView textEndTime;
    Calendar calendarStart;
    Calendar calendarEnd;

    @BindView(R.id.edit_gna)
    TextView edit_gna;
    @BindView(R.id.edit_gcd)
    TextView edit_gcd;



    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    public void initViews() {
        setContentView(R.layout.ware_list_activity);
        setTitle(""+ MyUtils.getHomeSelectName());
        setTitleLeftButton(null);
        LinearLayoutManager layoutManager = new LinearLayoutManager(mContext);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setVerticalScrollBarEnabled(true);
        mRecyclerView.setLayoutManager(layoutManager);
        mRecyclerView.setRefreshProgressStyle(ProgressStyle.BallSpinFadeLoader);
        mRecyclerView.setLoadingMoreProgressStyle(ProgressStyle.BallRotate);
        mRecyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                mListBean.refresh();
                getList();
            }

            @Override
            public void onLoadMore() {
                getList();
            }
        });
        mRecyclerView.setPullRefreshEnabled(true);
        mRecyclerView.setLoadingMoreEnabled(true);

        setTitleRightButton(R.mipmap.icon_multi, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (view_multi.getVisibility()){
                    case View.VISIBLE:
                        view_multi.setAnimation(AnimationUtils.loadAnimation(mContext, R.anim.top_out));
                        view_multi.setVisibility(View.GONE);
                        break;
                    case View.GONE:
                        view_multi.setAnimation(AnimationUtils.loadAnimation(mContext, R.anim.top_in));
                        view_multi.setVisibility(View.VISIBLE);
                        break;
                }
            }
        });
        setTitleRightButton2(R.mipmap.icon_rfid, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ActivityTool.skipActivity(mContext,ResetWareInfoActivity.class);

            }
        });
        initCalendar();
        initLglLabel();
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);
        mListBean = new WareListBean();
        setListView();
        setTitleLeftButton(null);
        mRecyclerView.refresh();
    }

    private void  initCalendar(){
        calendarStart = Calendar.getInstance();
        calendarStart.add(Calendar.MONTH, 0);
        calendarStart.set(Calendar.DAY_OF_MONTH, 1);
        calendarEnd = Calendar.getInstance();
        calendarEnd.set(Calendar.HOUR_OF_DAY,0);
        calendarEnd.set(Calendar.MINUTE,0);
        calendarEnd.set(Calendar.SECOND,0);
        calendarEnd.set(Calendar.MILLISECOND,0);
        textStartTime.setText(calendarStart == null? "": TimeUtils.getTimeByDate(calendarStart.getTime(), "yyyy-MM-dd"));
        textEndTime.setText(calendarEnd == null? "":TimeUtils.getTimeByDate(calendarEnd.getTime(), "yyyy-MM-dd"));
    }


    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    private void  initLglLabel(){
        lglLabel.setMulEnable(false);
        lglLabel.setColumnCount(3);
        lglLabel.setLabelBg(R.drawable.flow_popup);
        lglLabel.filterBeanListsAdd("仓库", GreenDaoUtils.getLocationListBean().getAllLocationSna());
        lglLabel.filterBeanListsAdd("货品分类", GreenDaoUtils.getSpeciesListBean().getAllNameList());
        lglLabel.filterBeanListsAdd("工艺", GreenDaoUtils.getCraftListBean().getAllNameList());
        lglLabel.setGridData(lglLabel.getFilterBeanLists());
    }

    @OnClick(R.id.tv_confirm)
    public void confirmBtn(){
        mRecyclerView.refresh();
        multiBtn();
    }
    @OnClick(R.id.tv_reset)
    public void resetBtn(){
        lglLabel.resetData();
    }
    @OnClick(R.id.icon_multi)
    public void multiBtn(){
        switch (view_multi.getVisibility()){
            case View.VISIBLE:
                view_multi.setAnimation(AnimationUtils.loadAnimation(mContext, R.anim.top_out));
                view_multi.setVisibility(View.GONE);
                break;
            case View.GONE:
                view_multi.setAnimation(AnimationUtils.loadAnimation(mContext, R.anim.top_in));
                view_multi.setVisibility(View.VISIBLE);
                break;
        }
    }


    private void setListView() {
        if (mAdapter == null) {
            mAdapter = new MyAdapterList();
            mRecyclerView.setAdapter(mAdapter);
        } else {
            mAdapter.notifyDataSetChanged();
        }
    }

    private void onListViewComplete() {
        mRecyclerView.refreshComplete();
        mRecyclerView.loadMoreComplete();
        mRecyclerView.setLoadingMoreEnabled(mListBean.hasNextPage());
//        mRecyclerView.setLoadingMoreEnabled(false);
        setEmptyView();
    }

    private void setEmptyView() {
        if (mListBean == null || mListBean.getList().size() == 0) {
            findViewById(R.id.refresh_view).setVisibility(View.VISIBLE);
            findViewById(R.id.refresh_view).setOnClickListener(
                    new View.OnClickListener() {
                        public void onClick(View v) {
                            mRecyclerView.refresh();
                        }
                    });
        } else {
            findViewById(R.id.refresh_view).setVisibility(View.INVISIBLE);
        }
    }

    @OnClick(R.id.img_search)
    public void search(){
        mRecyclerView.refresh();
    }


    String curCid ="";
    String curCTy;
    private void getList() {

        MyParams params = new MyParams();
        showProgress();
        params.put("aid", LoginBean.getInstance().getAcode());

        if(lglLabel != null && lglLabel.getLabelData().size()>0){
            for(String mul :lglLabel.getLabelData()){
                if(mul.contains("仓库") && !mul.contains("不限")){
                    params.put("loc", SplitUtil.split(mul,"-",1));
                }
                if(mul.contains("货品分类")&& !mul.contains("不限")){
                    params.put("tid", GreenDaoUtils.getTidBySnaFromSpecies(SplitUtil.split(mul,"-",1)));

                }
                if(mul.contains("工艺")&& !mul.contains("不限")){
                    curCid =GreenDaoUtils.getCidByName(SplitUtil.split(mul,"-",1));
                    params.put("cid", curCid);
                    curCTy = SplitUtil.split(mul,"-",1);
                }
            }
        }

        if(!TextUtils.isEmpty(edit_gna.getText().toString())){
            params.put("gna", edit_gna.getText().toString().trim());
        }
        if(!TextUtils.isEmpty(edit_gcd.getText().toString())){
            params.put("gcd", edit_gcd.getText().toString().trim());
        }



//        params.put("bstime", textStartTime.getText().toString().trim());
//        params.put("betime", textEndTime.getText().toString().trim());
        params.put(BaseListBeanXF.PAGE_NAME, mListBean.getNextPage());
        params.put(BaseListBeanXF.PAGE_SIZE_NAME, BaseListBeanXF.PAGE_SIZE);

        MyHttpUtils.get(Constants.URL_STOCK_GET_SELECT_PAGE, params, new MyHttpListener() {
                    @Override
                    public void onSuccess(int httpWhat, Object result) {
                        if (isFinishing()) return;
                        WareListBean bean = (WareListBean)result;
                        mListBean.addListBean(bean);
                        setListView();
                    }

                    @Override
                    public void onFailure(int httpWhat, Object result) {
                        super.onFailure(httpWhat, result);
                        setListView();
                    }

                    @Override
                    public void onFinish(int httpWhat) {
                        dismissProgress();
                        onListViewComplete();
                    }
                },
                0, WareListBean.class);

    }




    public class MyAdapterList extends RecyclerView.Adapter<MyAdapterList.ViewHolder> {

        public MyAdapterList() {

        }

        //创建新View，被LayoutManager所调用
        @Override
        public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
            View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.ware_list_item, viewGroup, false);
            return new ViewHolder(view);
        }

        //将数据与界面进行绑定的操作
        @Override
        public void onBindViewHolder(ViewHolder viewHolder, int position) {
            viewHolder.bind(position);
        }

        //获取数据的数量
        @Override
        public int getItemCount() {
            return mListBean == null ? 0 : mListBean.getList().size();
        }

        //自定义的ViewHolder，持有每个Item的的所有界面元素
        public class ViewHolder extends RecyclerView.ViewHolder {
            @BindView(R.id.list_item)
            public View list_item;
            @BindView(R.id.text_rfid)
            public TextView text_rfid;
            @BindView(R.id.text_gna)
            public TextView text_gna;
            @BindView(R.id.text_wms2)
            public TextView text_wms2;
            @BindView(R.id.text_gcd)
            public TextView text_gcd;
            @BindView(R.id.text_gno)
            public TextView text_gno;
            @BindView(R.id.text_gsp)
            public TextView text_gsp;
            @BindView(R.id.text_gwtp)
            public TextView text_gwtp;
            @BindView(R.id.text_gnu1)
            public TextView text_gnu1;
            @BindView(R.id.btn_delete)
            public TextView btn_delete;
            @BindView(R.id.btn_edit)
            public TextView btn_edit;


            public ViewHolder(View view) {
                super(view);
                ButterKnife.bind(this, view);
            }

            public void bind(int position) {
                WareListData data = mListBean.getList().get(position);
                MyUtils.setNotNullText(text_rfid,data.getRfid());
                MyUtils.setNotNullText(text_gna,data.getGna());
                MyUtils.setNotNullText(text_wms2,data.getWms2());
                MyUtils.setNotNullText(text_gcd,data.getGcd());
                MyUtils.setNotNullText(text_gno,data.getGno());
                MyUtils.setNotNullText(text_gsp,data.getGsp());
                MyUtils.setNotNullText(text_gwtp,""+data.getGwtp());
                MyUtils.setNotNullText(text_gnu1,""+data.getGnu1());
                if(curCTy.equals("期初")){
                    btn_edit.setVisibility(View.VISIBLE);
                }else {
                    btn_edit.setVisibility(View.GONE);
                }
                list_item.setTag(position);
                btn_delete.setTag(position);
                btn_edit.setTag(position);

            }
            @OnClick(R.id.btn_delete)
            void onItemDelClick(View view){
                if (!OnClickUtils.isFastClick()) {
                    // 进行点   击事件后的逻辑操作
                    int position = (int) view.getTag();
                    WareListData data = mListBean.getList().get(position);
                    EditWareInfoActivity.toEdit(mContext,curCid,data,WARNLISTRESULT);
                }
            }

            @OnClick(R.id.btn_edit)
            void onItemEditClick(View view){
                if (!OnClickUtils.isFastClick()) {
                    // 进行点   击事件后的逻辑操作
                    int position = (int) view.getTag();
                    WareListData data = mListBean.getList().get(position);
                    EditWareInfoActivity.toEdit(mContext,curCid,data,WARNLISTRESULT);
                }
            }
        }
    }

    public final static int WARNLISTRESULT = 44;
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == WARNLISTRESULT){
            mRecyclerView.refresh();
        }
    }




    @OnClick(R.id.view_filter_1)
    void timeBeginChoose() {
        //时间选择器
        TimePickerView pvTime = new TimePickerBuilder(mContext, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
                if (calendarStart == null) {
                    calendarStart = Calendar.getInstance();
                }
                calendarStart.setTime(date);
                onTimeBeginChoosed();
            }
        })
                .addOnCancelClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                    }
                })
                .setType(new boolean[]{true, true, true, false, false, false})// 默认全部显示
                .build();
        pvTime.show();
        ViewUtils.hideInput(mContext);
    }


    void onTimeBeginChoosed() {
        textStartTime.setText(calendarStart == null? "":TimeUtils.getTimeByDate(calendarStart.getTime(), "yyyy-MM-dd"));
        if(calendarStart != null && calendarEnd != null){
            mRecyclerView.refresh();
        }else if(calendarStart == null && calendarEnd == null){
            mRecyclerView.refresh();
        }
    }

    @OnClick(R.id.view_filter_2)
    void timeEndChoose() {
        //时间选择器
        TimePickerView pvTime = new TimePickerBuilder(mContext, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
                if (calendarEnd == null) {
                    calendarEnd = Calendar.getInstance();
                }
                calendarEnd.setTime(date);
                onTimeEndChoosed();
            }
        }).addOnCancelClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        })
                .setType(new boolean[]{true, true, true, false, false, false})// 默认全部显示
                .build();
        pvTime.show();
        ViewUtils.hideInput(mContext);
    }

    void onTimeEndChoosed() {
        textEndTime.setText(calendarEnd == null? "":TimeUtils.getTimeByDate(calendarEnd.getTime(), "yyyy-MM-dd"));
        if(calendarStart != null && calendarEnd != null){
            mRecyclerView.refresh();
        }else if(calendarStart == null && calendarEnd == null){
            mRecyclerView.refresh();
        }
    }


}
